<?php defined('SYSPATH') or die('No direct script access.');

/**
 * PC 端支付宝即时交易
 * Class Pay_Pc_alipay
 */
class Pay_Pc_AlipayCash
{
    //支付宝即时交易目录
    private $_alipayCashDir;
    //异步通知
    const NOTIFY_URL = '/callback/index/Pay_Pc_AlipayCash-notify_url/';
    //同步通知
    const ERTURN_URL = '/callback/index/Pay_Pc_AlipayCash-return_url/';

    public function __construct()
    {
        $this->_alipayCashDir = Common::C('interface_path') . 'pc/alipay_cash/';
    }

    public function submit($data)
    {
        require_once($this->_alipayCashDir . "lib/alipay_submit.class.php");
        $aliPay = new AlipaySubmit();
        //https://open.alipay.com 账户中心->密钥管理->开放平台密钥，填写添加了电脑网站支付的应用的APPID
        $appid = trim(Common::C('cfg_alipay_appid'));
        //付款成功后的同步回调地址
        $returnUrl = Common::C('base_url') . self::ERTURN_URL;
        //付款成功后的异步回调地址
        $notifyUrl = Common::C('base_url') . self::NOTIFY_URL;
        //你自己的商品订单号，不能重复
        $outTradeNo = $data['ordersn'];
        //付款金额，单位:元
        $payAmount = $data['total'];
        //订单标题
        $orderName = $data['ordersn'];
        //签名算法类型，支持RSA2和RSA，推荐使用RSA2
        $signType = 'RSA2';
        //商户私钥，填写对应签名算法类型的私钥，如何生成密钥参考：https://docs.open.alipay.com/291/105971和https://docs.open.alipay
        $rsaPrivateKey=Common::C('merchant_private_key');
        $aliPay->setAppid($appid);
        $aliPay->setReturnUrl($returnUrl);
        $aliPay->setNotifyUrl($notifyUrl);
        $aliPay->setRsaPrivateKey($rsaPrivateKey);
        $aliPay->setTotalFee($payAmount);
        $aliPay->setOutTradeNo($outTradeNo);
        $aliPay->setOrderName($orderName);
        $aliPay->setSignType($signType);
        $sHtml = $aliPay->doPay();
        echo $sHtml;
    }

    /**
     * 服务器异步通知页面路径
     * "gmt_create": "2021-12-07 11:26:08",
    "charset": "utf8",
    "gmt_payment": "2021-12-07 11:26:13",
    "notify_time": "2021-12-07 11:26:13",
    "subject": "11421120711260064440",
    "sign": "JdGt/TTFkESZXGjmvFjSVDYqpxwwQTmK4n9JbeJlgGQBqrPoBN6ogFYugHwucUcQ7A05mL2//EI9omyydWXF4U165JGk/1q/oC4qk3ZA1Cr0BWrAzj9+4j33GsitDLrPLpYtxA8yIKFU0K8U4RsoMFbscrazn8OG2NIw7PKFZ1FNHm/NLtwXFwP0TkBJ5VCvQ9XcMi1qVE1cUl6eGLv7axJKZpE/kU2/uiOPx6tOdf3g7ESHREgXXYHUxwQkT7L7dhs4nsxoaoqyCUVPtxqQa4TmIyLfVssx9leEjrAKQFytVL48JnVvojr8TjNcmqXYZ0ycYDbdvDM6t/uJ+RyK0w==",
    "buyer_id": "2088112729103664",
    "invoice_amount": "0.01",
    "version": "1.0",
    "notify_id": "2021120700222112613003661425423801",
    "fund_bill_list": "[{\"amount\":\"0.01\",\"fundChannel\":\"ALIPAYACCOUNT\"}]",
    "notify_type": "trade_status_sync",
    "out_trade_no": "11421120711260064440",
    "total_amount": "0.01",
    "trade_status": "TRADE_SUCCESS",
    "trade_no": "2021120722001403661432878529",
    "auth_app_id": "2021001159660839",
    "receipt_amount": "0.01",
    "point_amount": "0.00",
    "buyer_pay_amount": "0.01",
    "app_id": "2021001159660839",
    "sign_type": "RSA2",
    "seller_id": "2088631043045536"
     */
    public function notify_url()
    {
        header('Content-type:text/html; Charset=utf-8');
        include($this->_alipayCashDir . 'lib/alipay_notify.class.php');
        //支付宝公钥，账户中心->密钥管理->开放平台密钥，找到添加了支付功能的应用，根据你的加密类型，查看支付宝公钥
        $alipayPublicKey=Common::C('alipay_public_key');
        $aliPay = new AlipayNotify($alipayPublicKey);
        //验证签名
        $result = $aliPay->rsaCheck($_POST);
        if($result===true){
            //处理你的逻辑，例如获取订单号$_POST['out_trade_no']，订单金额$_POST['total_amount']等
            //程序执行完后必须打印输出“success”（不包含引号）。如果商户反馈给支付宝的字符不是success这7个字符，支付宝服务器会不断重发通知，直到超过24小时22分钟。一般情况下，25小时以内完成8次通知（通知的间隔频率一般是：4m,10m,10m,1h,2h,6h,15h）；
            if ($_POST['trade_status'] == 'TRADE_SUCCESS')
            {
                $tip = '信息:支付宝即时交易(异),订单金额与实际支付不一致';
                if (Common::total_fee_confirm($_POST['out_trade_no'], $_POST['total_amount'], $tip))
                {
                    $method = Common::C('pc');
                    Common::pay_success($_POST['out_trade_no'], $method['method']['11']['name']);
                    //写入支付宝流水号
                    $online_transaction_no = array('source'=>'alipay','transaction_no'=>$_POST['trade_no']);
                    DB::update('member_order')->set(array('online_transaction_no'=>json_encode($online_transaction_no)))
                        ->where('ordersn','=',$_POST['out_trade_no'])
                        ->execute();
                }
            }
            else
            {
                new Pay_Exception("状态:{$_POST['trade_status']}");
            }
            echo 'success';
            exit();
        }
        echo 'error';
        new Pay_Exception("信息:合法性验证失败");
        exit();
    }

    /**
     * 页面跳转同步通知页面路径
     * "charset": "utf8",
    "out_trade_no": "11421120711402028626",
    "method": "alipay.trade.page.pay.return",
    "total_amount": "0.01",
    "sign": "ZJUh7kmUKAQ9zWGAAu5RmVgLeUYVVdiMFwjAVFmVFlKqP4TdoimJwZokkIg2FIvl7sl0HrlnnNfpVZcArr/N1JrZpQHJiR2GVjKk9ajme0OG0BZ4ZbWl1nOjfMmKPjOUiz+3TgDAAq1BRkdpmtBGt318ej4/F5KOoOgOvgjyIlPf7xyhgo3E70oXrb4Fm1Ct8KLhE91mSZwkp7nhLamK9UVePlzcCpYxhRPDYYzb0t01ydB6zRol3tXKI4Ydr+e6dag/KHNn6IVW871BSJkbfBzoe7ojaWa4UR8TnpgBBtk0U3yDUGtszmW/IbnXCj2TY+fzbcwRBeLHxPpcob36Bg==",
    "trade_no": "2021120722001403661432967227",
    "auth_app_id": "2021001159660839",
    "version": "1.0",
    "app_id": "2021001159660839",
    "sign_type": "RSA2",
    "seller_id": "2088631043045536",
    "timestamp": "2021-12-07 11:40:45"
     */
    public function return_url()
    {
        header('Content-type:text/html; Charset=utf-8');
        include($this->_alipayCashDir . 'lib/alipay_notify.class.php');
        //支付宝公钥，账户中心->密钥管理->开放平台密钥，找到添加了支付功能的应用，根据你的加密类型，查看支付宝公钥
        $alipayPublicKey=Common::C('alipay_public_key');
        $aliPay = new AlipayNotify($alipayPublicKey);
        //验证签名
        $result = $aliPay->rsaCheck($_GET);
        if ($result) {
            $info['sign'] = '11';
        } else {
            $info['sign'] = '22';
            new Pay_Exception("状态:支付宝即时交易(同)数据有效性验证失败");
        }
        $info['ordersn'] = $_GET['out_trade_no'];
        Common::pay_status($info);
    }
}